import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../../core/constants/app_constants.dart';
import '../providers/theme_provider.dart';
import '../providers/content_filter_provider.dart';
import '../../core/utils/content_filter.dart';
import 'cache_management_page.dart'; // 添加缓存管理页面导入
import '../providers/anime_provider.dart';

/// 设置页面
class SettingsPage extends StatefulWidget {
  const SettingsPage({super.key});

  @override
  State<SettingsPage> createState() => _SettingsPageState();
}

class _SettingsPageState extends State<SettingsPage> with AutomaticKeepAliveClientMixin {
  @override
  bool get wantKeepAlive => true;

  @override
  Widget build(BuildContext context) {
    super.build(context);
    
    return Scaffold(
      body: CustomScrollView(
        slivers: [
          SliverAppBar(
            expandedHeight: 120,
            pinned: true,
            backgroundColor: Theme.of(context).colorScheme.surface,
            flexibleSpace: FlexibleSpaceBar(
              title: Text(
                '设置',
                style: TextStyle(
                  color: Theme.of(context).colorScheme.onSurface,
                  fontSize: 20,
                  fontWeight: FontWeight.bold,
                ),
              ),
            ),
          ),
          SliverList(
            delegate: SliverChildListDelegate([
              _buildSettingsSection(
                context,
                title: '外观',
                children: [
                  _buildThemeSettingTile(context),
                ],
              ),
              _buildSettingsSection(
                context,
                title: '内容过滤',
                children: [
                  _buildContentFilterTile(context),
                ],
              ),
              _buildSettingsSection(
                context,
                title: '数据',
                children: [
                  _buildCacheManagementTile(context),
                ],
              ),
              _buildSettingsSection(
                context,
                title: '关于',
                children: [
                  _buildAboutTile(context),
                  _buildVersionTile(context),
                ],
              ),
              const SizedBox(height: 24),
              
              // 缓存状态诊断
              Card(
                child: Padding(
                  padding: const EdgeInsets.all(16),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        '缓存状态诊断',
                        style: Theme.of(context).textTheme.titleMedium?.copyWith(
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                      const SizedBox(height: 16),
                      
                      ElevatedButton(
                        onPressed: () => _showCacheStatus(context),
                        child: const Text('查看缓存状态'),
                      ),
                      
                      const SizedBox(height: 8),
                      
                      ElevatedButton(
                        onPressed: () => _showHomePageCacheStatus(context),
                        child: const Text('查看主页缓存状态'),
                      ),
                    ],
                  ),
                ),
              ),
            ]),
          ),
        ],
      ),
    );
  }

  Widget _buildSettingsSection(
    BuildContext context, {
    required String title,
    required List<Widget> children,
  }) {
    return Padding(
      padding: const EdgeInsets.all(16),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Padding(
            padding: const EdgeInsets.only(left: 16, bottom: 8),
            child: Text(
              title,
              style: Theme.of(context).textTheme.titleSmall?.copyWith(
                    color: Theme.of(context).colorScheme.primary,
                    fontWeight: FontWeight.bold,
                  ),
            ),
          ),
          Card(
            child: Column(children: children),
          ),
        ],
      ),
    );
  }

  Widget _buildThemeSettingTile(BuildContext context) {
    return Consumer<ThemeProvider>(
      builder: (context, themeProvider, child) {
        return ListTile(
          leading: Icon(
            themeProvider.isDarkMode ? Icons.dark_mode : Icons.light_mode,
            color: Theme.of(context).colorScheme.primary,
          ),
          title: const Text('深色模式'),
          subtitle: Text(themeProvider.isDarkMode ? '已开启' : '已关闭'),
          trailing: Switch(
            value: themeProvider.isDarkMode,
            onChanged: (value) {
              themeProvider.toggleTheme();
            },
          ),
        );
      },
    );
  }

  Widget _buildCacheManagementTile(BuildContext context) {
    return ListTile(
      leading: Icon(
        Icons.storage,
        color: Theme.of(context).colorScheme.primary,
      ),
      title: const Text('缓存管理'),
      subtitle: const Text('管理应用缓存数据'),
      trailing: const Icon(Icons.arrow_forward_ios),
      onTap: () {
        Navigator.push(
          context,
          MaterialPageRoute(
            builder: (context) => const CacheManagementPage(),
          ),
        );
      },
    );
  }

  Widget _buildAboutTile(BuildContext context) {
    return ListTile(
      leading: Icon(
        Icons.info,
        color: Theme.of(context).colorScheme.primary,
      ),
      title: const Text('关于应用'),
      subtitle: const Text('AniQuest - 你的动漫追番助手'),
      trailing: const Icon(Icons.arrow_forward_ios),
      onTap: () {
        showAboutDialog(
          context: context,
          applicationName: 'AniQuest',
          applicationVersion: '1.0.0',
          applicationIcon: const Icon(Icons.animation, size: 48),
          children: [
            const Text('一个精美的动漫信息应用'),
            const SizedBox(height: 16),
            const Text('数据来源: Jikan API (MyAnimeList)'),
          ],
        );
      },
    );
  }

  Widget _buildContentFilterTile(BuildContext context) {
    return Consumer<ContentFilterProvider>(
      builder: (context, filterProvider, child) {
        return ListTile(
          leading: Icon(
            Icons.shield,
            color: Theme.of(context).colorScheme.primary,
          ),
          title: const Text('内容过滤'),
          subtitle: Text('当前级别: ${filterProvider.filterLevelDescription}'),
          trailing: const Icon(Icons.arrow_forward_ios),
          onTap: () => _showContentFilterDialog(context, filterProvider),
        );
      },
    );
  }

  void _showContentFilterDialog(BuildContext context, ContentFilterProvider filterProvider) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('内容过滤设置'),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            const Text(
              '选择内容过滤级别，以控制显示的动漫内容类型：',
              style: TextStyle(fontSize: 14),
            ),
            const SizedBox(height: 16),
                         ...FilterLevel.values.map((level) {
               return RadioListTile<FilterLevel>(
                title: Text(ContentFilter.getFilterLevelDescription(level)),
                subtitle: Text(_getFilterLevelDetail(level)),
                value: level,
                groupValue: filterProvider.filterLevel,
                onChanged: (value) {
                  if (value != null) {
                    filterProvider.setFilterLevel(value);
                    Navigator.of(context).pop();
                    
                    // 显示提示信息
                    ScaffoldMessenger.of(context).showSnackBar(
                      SnackBar(
                        content: Text('内容过滤级别已设置为：${ContentFilter.getFilterLevelDescription(value)}'),
                        duration: const Duration(seconds: 2),
                      ),
                    );
                  }
                },
              );
            }).toList(),
          ],
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: const Text('取消'),
          ),
        ],
      ),
    );
  }

  String _getFilterLevelDetail(FilterLevel level) {
    switch (level) {
      case FilterLevel.none:
        return '显示所有内容，包括成人内容';
      case FilterLevel.basic:
        return '过滤明显的成人内容（推荐）';
      case FilterLevel.strict:
        return '严格过滤所有可能不适宜的内容';
    }
  }

  Widget _buildVersionTile(BuildContext context) {
    return ListTile(
      leading: Icon(
        Icons.code,
        color: Theme.of(context).colorScheme.primary,
      ),
      title: const Text('版本信息'),
      subtitle: const Text('1.0.0'),
      trailing: const Icon(Icons.arrow_forward_ios),
    );
  }

  void _showCacheStatus(BuildContext context) async {
    try {
      final animeProvider = Provider.of<AnimeProvider>(context, listen: false);
      final cacheStatus = await animeProvider.getCacheStatus();
      
      if (!context.mounted) return;
      
      showDialog(
        context: context,
        builder: (context) => AlertDialog(
          title: const Text('缓存状态'),
          content: SingleChildScrollView(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              mainAxisSize: MainAxisSize.min,
              children: [
                Text('总条目数: ${cacheStatus['total_entries'] ?? 0}'),
                Text('列表缓存: ${cacheStatus['list_entries'] ?? 0}'),
                Text('详情缓存: ${cacheStatus['detail_entries'] ?? 0}'),
                Text('缓存大小: ${cacheStatus['cache_size_mb'] ?? 0} MB'),
                Text('缓存有效期: ${cacheStatus['cache_valid_duration_minutes'] ?? 0} 分钟'),
                const SizedBox(height: 16),
                Text('最旧缓存: ${cacheStatus['oldest_entry'] ?? '无'}'),
                Text('最新缓存: ${cacheStatus['newest_entry'] ?? '无'}'),
              ],
            ),
          ),
          actions: [
            TextButton(
              onPressed: () => Navigator.pop(context),
              child: const Text('关闭'),
            ),
          ],
        ),
      );
    } catch (e) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('获取缓存状态失败: $e')),
      );
    }
  }

  void _showHomePageCacheStatus(BuildContext context) async {
    try {
      final animeProvider = Provider.of<AnimeProvider>(context, listen: false);
      final homePageStatus = await animeProvider.getCacheStatus();
      
      if (!context.mounted) return;
      
      showDialog(
        context: context,
        builder: (context) => AlertDialog(
          title: const Text('主页缓存状态'),
          content: SingleChildScrollView(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              mainAxisSize: MainAxisSize.min,
              children: [
                Text('热门推荐数量: ${animeProvider.trendingAnime.length}'),
                Text('即将上线数量: ${animeProvider.upcomingAnime.length}'),
                Text('本季新番数量: ${animeProvider.seasonalAnime.length}'),
                Text('最新更新数量: ${animeProvider.recentEpisodes.length}'),
                const SizedBox(height: 16),
                const Text('具体数据状态:', style: TextStyle(fontWeight: FontWeight.bold)),
                Text('loading: ${animeProvider.isLoading}'),
                Text('hasError: ${animeProvider.hasError}'),
                if (animeProvider.hasError) Text('错误: ${animeProvider.errorMessage}'),
              ],
            ),
          ),
          actions: [
            TextButton(
              onPressed: () async {
                Navigator.pop(context);
                // 强制刷新所有数据
                await animeProvider.fetchTrendingAnime(refresh: true);
                await animeProvider.fetchUpcomingAnime(refresh: true);
                await animeProvider.fetchSeasonalAnime(refresh: true);
                await animeProvider.fetchRecentEpisodes();
                
                if (context.mounted) {
                  ScaffoldMessenger.of(context).showSnackBar(
                    const SnackBar(content: Text('已刷新主页数据')),
                  );
                }
              },
              child: const Text('刷新数据'),
            ),
            TextButton(
              onPressed: () => Navigator.pop(context),
              child: const Text('关闭'),
            ),
          ],
        ),
      );
    } catch (e) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('获取主页缓存状态失败: $e')),
      );
    }
  }
} 